package com.voxel.sense.infomsg.module.firm.details.general;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.ToastUtil;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.download.DownloadListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.FirmTableInfoBean;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.OpenDocuIntentUtils;
import com.voxel.sense.infomsg.utils.UploadUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.CommonConstants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.FirmGeneralInfoEntity;
import cyy.example.com.facotry.net.helper.FirmNetHelper;
import retrofit2.Call;

/**
 * Created by ChenYiYao on 2018/3/1.
 */

public class FirmGeneralPresenter extends BasePresenter<FirmGeneralContract.View>
        implements FirmGeneralContract.Presenter, DataSource.Callback<BaseEntity<FirmGeneralInfoEntity>> {

    private Call mCall;
    private boolean mIsLoading = false;

    public FirmGeneralPresenter(FirmGeneralContract.View view) {
        super(view);
    }

    @Override
    public void start() {
        super.start();
        EventBus.getDefault().register(this);
    }


    @Override
    public void doLoadData(String id) {
        FirmNetHelper.getFirmGeneralInfo(id, this);
        mView.showLoading("");

    }

    @Override
    public void onDataLoaded(BaseEntity<FirmGeneralInfoEntity> data, int reqId) {
        if (mView == null) {
            return;
        }

        if (data != null && data.isSuccess()) {
            FirmGeneralInfoEntity entity = data.getData();
            if (entity != null) {
                //构建表格的数据
                createTabableData(entity);
            }
        }

        if (mView != null)
            mView.dimissLoading();
    }

    private void createTabableData(FirmGeneralInfoEntity data) {
        List<FirmTableInfoBean> dataList = new ArrayList<>();
        FirmGeneralInfoEntity.CompanyBaseinfoVoBean baseInfo = data.getCompanyBaseinfoVo();

        dataList.add(new FirmTableInfoBean(FirmTableInfoBean.TYPE_HEAD, "生产工艺流程",
                baseInfo.getProcessFlow()));

        List<FirmGeneralInfoEntity.CompanyPollTotalListBean> totalList = data.getCompanyPollTotalList();
        if (totalList != null && totalList.size() > 0) {
            FirmTableInfoBean bean = new FirmTableInfoBean(FirmTableInfoBean.TYPE_HEAD_EXPAND, "企业主要污染物", "执行标准");
            for (FirmGeneralInfoEntity.CompanyPollTotalListBean Totalbean : totalList) {
                bean.addSubItem(new FirmTableInfoBean(FirmTableInfoBean.TYPE_NORMAL,
                        Totalbean.getPollutantType(), Totalbean.getPollutantStandard()));

            }
            dataList.add(bean);
        }

        List<FirmGeneralInfoEntity.CompanyPollDeviceListBean> deviceList = data.getCompanyPollDeviceList();
        if (deviceList != null && deviceList.size() > 0) {
            FirmTableInfoBean bean = new FirmTableInfoBean(FirmTableInfoBean.TYPE_HEAD_EXPAND, "污染处理设施", "设施执行能力");
            for (FirmGeneralInfoEntity.CompanyPollDeviceListBean deviceBean : deviceList) {
                bean.addSubItem(new FirmTableInfoBean(FirmTableInfoBean.TYPE_NORMAL, deviceBean.getDevName(),
                        deviceBean.getDevCapacity()));
            }
            dataList.add(bean);
        }

        List<FirmGeneralInfoEntity.CompanyFileVoBean> companyFileVo = data.getCompanyFileVo();
        if (companyFileVo != null && companyFileVo.size() > 0) {
            dataList.add(new FirmTableInfoBean(FirmTableInfoBean.TYPE_URL, "排污许可证", companyFileVo.get(0).getFilePath()));
        }
        //更新数据
        if (mView != null)
            mView.onRefreshData(dataList);
    }


    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView != null)
            mView.showError(strRes);

    }

    @Override
    public void destroy() {
        if (mCall != null)
            mCall.cancel();

        EventBus.getDefault().unregister(this);
        super.destroy();
    }

    @Subscribe
    public void onEventBus(EventEntity event) {
        if (EventBusConstants.DOWN_FIRM_LICENSE.equals(event.key)) {//下载文件的消息
            String value = (String) event.value;
            OpenFile(CommonConstants.FILE_FIRM_URL, value);
        }  else if (EventBusConstants.LOAD_FIRM_DATA_FAILURE.equals(event.key)) {//刷新数据失败
            if (mView != null)
                mView.showError(String.valueOf(event.value));
        }
    }


    private void OpenFile(String url, String fileName) {
        File cacheDir = AppFileUtil.getCacheDir();
        File file = new File(cacheDir, fileName);
        boolean fileExists = FileUtils.isFileExists(new File(cacheDir, fileName));
        if (fileExists) {
            OpenDocuIntentUtils.OpenFile(file, Factory.app());
        } else {
            DownFile(url, fileName, cacheDir);
        }
    }

    private void DownFile(final String url, final String fileName, final File cacheDir) {
        if (!NetworkUtils.isConnected()) {
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.network_unavailable));
            return;
        }

        if (mIsLoading)
            return;

        UploadUtils.getInstent().getPostDownRequest(cacheDir.getAbsolutePath(), fileName, url + fileName, new DownloadListener(url + fileName) {
            @Override
            public void onStart(Progress progress) {
                if (mView == null)
                    return;
                mIsLoading = true;
                mView.onShowDownPogress();
            }

            @Override
            public void onProgress(Progress progress) {

            }

            @Override
            public void onError(Progress progress) {
                if (mView == null)
                    return;
                mIsLoading = false;
                mView.onDismissDownProgress();
                ToastUtil.showToastLong(Factory.app(), "下载失败");
                FileUtils.deleteAllFile(new File(cacheDir, fileName));
            }

            @Override
            public void onFinish(File file, Progress progress) {
                if (mView == null)
                    return;
                mIsLoading = false;
                mView.onDismissDownProgress();
                OpenDocuIntentUtils.OpenFile(file, Factory.app());
            }

            @Override
            public void onRemove(Progress progress) {

            }
        });
    }

}
